import { Spin, message } from 'antd'
import services from '@/services'
import type { BaseAccount } from '@/services/auth'
import type { AccountGroup } from '@/services/features/accounts'
import './index.module.less'

import Accounts from './Accounts'
import Groups from './Groups'

export default function AccountGroups() {
  const [accounts, setAccounts] = useState<BaseAccount[] | null>(null)
  const [groups, setGroups] = useState<AccountGroup[] | null>(null)
  const [selectedGroup, setSelectedGroup] = useState<null | AccountGroup>(null)
  useEffect(() => {
    void services.features.accounts.getAccounts(true).then(setAccounts)
    void services.features.accounts.getGroups().then(_groups => {
      setGroups(_groups)
      if (_groups.length) setSelectedGroup(_groups[0]!)
    })
  }, [])

  const refreshGroups = useCallback(() => {
    void services.features.accounts.getGroups().then(_groups => {
      setGroups(_groups)

      // 用新返回的 group 数据代替老的；如果原“当前 group”已不存在，重置“当前 group”
      if (selectedGroup) setSelectedGroup(_groups.find(v => v.id === selectedGroup.id) ?? null)
    })
  }, [selectedGroup])

  const addAccounts = useCallback(
    (ids: string[]) => {
      if (!selectedGroup) return
      void services.features.accounts.groupAddAccounts(selectedGroup, ids).then(res => {
        if (res === true) void message.success('成员添加成功')
        else void message.error(`成员添加失败：${res}`)
        refreshGroups()
      })
    },
    [selectedGroup, refreshGroups],
  )

  const removeAccounts = useCallback(
    (ids: string[]) => {
      if (!selectedGroup) return
      void services.features.accounts.groupRemoveAccounts(selectedGroup, ids).then(res => {
        if (res === true) void message.success('成员已移出分组')
        else void message.error(`成员移出失败：${res}`)
        refreshGroups()
      })
    },
    [selectedGroup, refreshGroups],
  )

  if (!accounts || !groups)
    return <div styleName="loading">
      <Spin tip="数据加载中..." />
    </div>

  return <div styleName="wrap">
    <Groups
      groups={groups}
      selectedId={selectedGroup?.id ?? null}
      select={setSelectedGroup}
      refresh={refreshGroups}
    />

    {selectedGroup ? (
      <Accounts
        all={accounts}
        ids={selectedGroup.accountIds}
        onAdd={addAccounts}
        onRemove={removeAccounts}
      />
    ) : null}
  </div>
}
